package com.c5p1ng.route.filter;

import com.c5p1ng.route.util.ContextUtil;
import com.c5p1ng.route.util.IPUtil;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
public class HeaderContentFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String headerStr = getRequestHeaderString(request);
        HeaderContentFilterHelper.initGlobalContext(headerStr, IPUtil.getClientAddress(request));
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            ContextUtil.clear();
        }
    }

    private String getRequestHeaderString(HttpServletRequest servletRequest) {
        return servletRequest.getHeader(ContextUtil.REQUEST_CONTEXT);
    }

    @Override
    public void destroy() {

    }

}
